<template>
	<view class="main">
		<u-upload :width='width + "rpx"' :height='height + "rpx"' :fileList="fileList1" @afterRead="afterRead"
			:capture="sourceType" :deletable="deletable" @delete="deletePic" name="1" multiple :maxCount="maxCount">
		</u-upload>
		<canvas type="2d" id="myCanvas" style="position: absolute;top: -9999999px; left: -9999999px;"></canvas>
	</view>
</template>

<script>
	import config from '@/common/config';
	export default {
		props: {
			width: {
				type: Number,
				default () {
					return 200;
				}
			},
			height: {
				type: Number,
				default () {
					return 200;
				}
			},
			maxCount: {
				type: Number,
				default () {
					return 9;
				}
			},
			list: {
				type: Array,
				default () {
					return [];
				}
			},
			fileType: {
				type: Number,
				default () {
					return 3;
				}
			},
			fileList: {
				type: Array,
				default () {
					return [];
				}
			},
			sourceType: {
				type: Array,
				default () {
					return ['album', 'camera'];
				}
			},
			deletable: {
				type: Boolean,
				default () {
					return true
				}
			}
		},
		data() {
			return {
				fileList1: this.fileList || [],
				maxSize: 500, // 图片宽高的最大尺寸
				myCanvas: null,
				myCtx: null,
				dpr: null,
				canvasDisplayW: 300,
				canvasDisplayH: 300,
				fillNum: 120
			}
		},
		watch: {
			fileList(newVal, oldVal) {
				this.fileList1 = [];
				if (newVal.length > 0) {
					newVal.forEach(s => {
						let dd = {
							status: 'success',
							message: '',
							url: s.url
						}
						this.fileList1.push(dd)
					})
				}

			}
		},
		onLoad() {

		},
		onShow() {

		},
		mounted() {
			this.initCanvas()
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.$emit("deletePicture", this.fileList1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.$emit("getdata", this.fileList1)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + `/base/upload/uploadFile`,
						filePath: url,
						name: 'file',
						formData: {
							type: this.fileType,
							file: url
						},
						header: {
							// #ifdef MP
							"Content-Type": "multipart/form-data",
							// #endif
							"API-User-Token": uni.getStorageSync('userInfo').token
						},
						success: (uploadFileRes) => {
							let res = JSON.parse(uploadFileRes.data);
							setTimeout(() => {
								resolve(res.data.fileIds[0])
							}, 500)
						}
					});
				})
			},
			initCanvas() {
				const _ = this;
				// 若在自定义组件中，此处应写为this.createSelectorQuery();
				const query = wx.createSelectorQuery();
				query.select('#myCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						let myCanvas = res[0].node;
						let myCtx = myCanvas.getContext('2d');
						myCtx.font = "normal bold 18px PingFangSC-Regular";
						const dpr = wx.getSystemInfoSync().pixelRatio;

						this.myCanvas = myCanvas
						this.myCtx = myCtx
						this.dpr = dpr
					})
			},
			// 压缩图片
			compress(imgW, imgH) {
				const _ = this;
				const dpr = _.dpr;
				const maxSize = _.maxSize;
				const ratio = imgW / imgH;
				let canvas = _.myCanvas;
				let ctx = _.myCtx;

				let canvasWidth = imgW;
				let canvasHeight = imgH;
				while (canvasWidth > maxSize || canvasHeight > maxSize) {
					if (canvasWidth > maxSize) {
						canvasWidth = maxSize;
						canvasHeight = maxSize / ratio;
					} else if (canvasHeight > maxSize) {
						canvasHeight = maxSize;
						canvasWidth = maxSize * ratio;
					}
				}
				canvas.width = dpr * canvasWidth;
				canvas.height = dpr * canvasHeight;
				ctx.scale(dpr, dpr);

				return {
					canvasWidth,
					canvasHeight
				}
			},
			// 图片添加水印
			addMask(img, imgW, imgH) {
				const _ = this;
				// const date = 'namename';
				const fillTexts = [];
				// fillTexts.push('用途：' + '打卡')
				fillTexts.push('时间：' + this.getNowTime())
				// fillTexts.push('地址：' + this.form.address)
				if (!_.myCanvas) {
					_.initCanvas();
				}
				let canvas = _.myCanvas;
				let ctx = _.myCtx;
				// 1. 压缩图片
				let {
					canvasWidth,
					canvasHeight
				} = _.compress(imgW, imgH);
				return new Promise((resolve, reject) => {
					// 2. 生成图片
					let image = canvas.createImage();
					image.src = img;
					image.onload = (e) => {
						// 3. 绘图
						ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
						ctx.fillStyle = '#222';
						ctx.shadowColor = "#333"; // 阴影颜色
						ctx.shadowOffsetX = 0; // 阴影x轴位移。正值向右，负值向左。
						ctx.shadowOffsetY = 0; // 阴影y轴位移。正值向下，负值向上。
						ctx.shadowBlur = 15; // 阴影模糊滤镜。数据越大，扩散程度越大。
						// fillTexts
						this.fillNum = 120
						fillTexts.forEach((mark, index) => {
							this.fillNum += 20
							ctx.fillText(mark, 10, this.fillNum += 10);
						});
						// 4. 将canvas转为图片
						wx.canvasToTempFilePath({
							destWidth: canvasWidth,
							destHeight: canvasHeight,
							canvas: canvas,
							success(res) {
								resolve(res.tempFilePath);
							},
							fail(error) {
								reject(error)
							}
						})
					}
					image.onerror = (e) => {
						console.error('创建图片错误', e)
					}
				})
			},
			// 选择图片
			chooseImage(imgPath) {
				const _ = this;
				let imgPathitem = imgPath[0]
				wx.getImageInfo({
					src: imgPath[0].url,
					success(res) {
						// 2. 添加水印
						_.addMask(imgPathitem.url, res.width, res.height).then(imgPath => {
							_.fileList1.push({
								size: imgPathitem.size,
								thumb: imgPath,
								type: imgPathitem.type,
								url: imgPath,
							})
						});
					},
					fail(res) {
						console.log("fail res", res);
					}
				})
				// 

			},
			getNowTime() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
			}
		}
	}
</script>

<style lang="scss">
	
</style>
